from gm.api import *
import os


def init(context):
    context.index = "SHSE.000016"
    context.num = 5
    schedule(schedule_func=algo, date_rule='1m', time_rule='09:31:00')


def algo(context):
    now = context.now
    order_close_all()

    symbol_list = get_history_constituents(index=context.index, start_date=now)[0].get('constituents').keys()

    df = get_fundamentals_n(table='deriv_finance_indicator', symbols=symbol_list, end_date=now, fields='NPGRT', count=1,
                            df=True)
    df = df.sort_values(['NPGRT'], ascending=False)

    target_list = df['symbol'].values
    target_list = target_list[:context.num]

    for symbol in target_list:
        order_target_percent(symbol=symbol, percent=1. / context.num, order_type=OrderType_Market,
                             position_side=PositionSide_Long)

    def on_backtest_finished(context, indicator):
        print(indicator)


if __name__ == '__main__':
    run(
        strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename=(os.path.basename(__file__)),
        # filename=('程序6_2策略.py'),
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2016-01-01 09:00:00',
        backtest_end_time='2018-12-31 15:00:00',
        backtest_initial_cash=20000,
        backtest_adjust=ADJUST_PREV,
    )
